﻿<!DOCTYPE html>
<html ng-app="directiveApp">
<head>
    <title></title>
    <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" />
    <script src="scripts/angular.min.js"></script>
    <script>
        angular.module("directiveApp", [])
            .directive("unorderedList", function () {   
                return function (scope, element, attrs) {
                    var data = scope[attrs["unorderedList"]];
                    if (angular.isArray(data)) {
                        var listElem = angular.element("<ul>");  // 使用jqLite创建一个ul元素
                        element.append(listElem);
                        for (var i = 0; i < data.length; i++) {
                            // 此处硬编码使用了对象的"name"属性。
                            // 一般在directive中尽量不要使用依赖于调用者的属性
                            // 下一个例子中将去除这种依赖性
                            listElem.append(angular.element('<li>').text(data[i].name));
                        }
                    }
                }
            })
            .controller("defaultCtrl", function ($scope) {
                $scope.products = [
                    { name: "Apples", category: "Fruit", price: 1.20, expiry: 10 },
                    { name: "Bananas", category: "Fruit", price: 2.42, expiry: 7 },
                    { name: "Pears", category: "Fruit", price: 2.02, expiry: 6 }
                ];
            });
    </script>
</head>
<body ng-controller="defaultCtrl">
    <div class="panel panel-default">
        <div class="panel-heading">
            <h3>Products</h3>
        </div>
        <div class="panel-body">
            <div unordered-list="products"></div>
        </div>
    </div>
</body>
</html>
